# 服务器端 (server.py)
import socket


def start_server():
    # 创建socket对象
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 获取本地主机名
    host = socket.gethostname()
    port = 9999

    # 绑定端口号
    server_socket.bind((host, port))

    # 设置最大连接数，超过后排队
    server_socket.listen(5)

    print(f"服务器启动，监听主机: {host}, 端口: {port}")

    # 服务器无限循环
    while True:
        # 建立客户端连接
        client_socket, addr = server_socket.accept()

        print(f"获取到连接来自: {addr}")

        # 向客户端发送消息
        msg = '欢迎访问服务器！' + "\r\n"
        client_socket.send(msg.encode('utf-8'))

        # 接收客户端消息
        client_data = client_socket.recv(1024)
        print(f"客户端消息: {client_data.decode('utf-8')}")

        # 关闭客户端连接
        client_socket.close()


if __name__ == '__main__':
    start_server()